﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using CommonBase;
using MCDomain.Model;
using MContracts.ViewModel;
using Microsoft.Win32;
using Telerik.Windows.Controls;
using Telerik.Windows.Data;

namespace MContracts.View
{
    /// <summary>
    /// Логика взаимодействия для ContractRepositoryViewBasedView.xaml
    /// </summary>
    public partial class ContractRepositoryViewBasedView : UserControl
    {
        private RadGridViewSettings _settings;

        public ContractRepositoryViewBasedView()
        {
            InitializeComponent();
            contractsDataGrid.GroupDescriptors.CollectionChanged +=
                new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
                    GroupDescriptors_CollectionChanged);
            contractsDataGrid.FilterDescriptors.CollectionChanged +=
                new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
                    GroupDescriptors_CollectionChanged);
            contractsDataGrid.SortDescriptors.CollectionChanged +=
                new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
                    GroupDescriptors_CollectionChanged);
          

        }

        private void GroupDescriptors_CollectionChanged(object sender,
                                                        System.Collections.Specialized.NotifyCollectionChangedEventArgs
                                                            e)
        {

            if (e.Action != NotifyCollectionChangedAction.Reset && !_settings.IsChanging)
                SaveState(true, true, true);

        }

        private void contractsDataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            LoadState();
            if (DataContext != null)
            {
                DataContext.CastTo<ContractRepositoryViewBasedViewModel>().RequestExportRegistry += new EventHandler(ContractRepositoryViewBasedView_RequestExportRegistry);
                SetContextItems();
            }

        }

        void ContractRepositoryViewBasedView_RequestExportRegistry(object sender, EventArgs e)
        {
            string extension = "xls";
            ExportFormat format = ExportFormat.Html;

            //RadComboBoxItem comboItem = ComboBox1.SelectedItem as RadComboBoxItem;
            //string selectedItem = comboItem.Content.ToString();

            //switch (selectedItem)
            //{
            //    case "Excel": extension = "xls";
            //format = ExportFormat.Html;
            ////        break;
            //    case "ExcelML": extension = "xml";
            //        format = ExportFormat.ExcelML;
            //        break;
            //    case "Word": extension = "doc";
            //        format = ExportFormat.Html;
            //        break;
            //    case "Csv": extension = "csv";
            //        format = ExportFormat.Csv;
            //        break;
            //}                        

            var dialog = new SaveFileDialog
                             {
                                 DefaultExt = extension,
                                 Filter =
                                     String.Format("{1} файлы (*.{0})|*.{0}|Все файлы (*.*)|*.*", extension,
                                                   "Microsoft Excel"),
                                 FilterIndex = 1
                             };

            if (dialog.ShowDialog() == true)
            {
                using (Stream stream = dialog.OpenFile())
                {
                    var exportOptions = new GridViewExportOptions
                                            {
                                                Format = format,
                                                ShowColumnFooters = true,
                                                ShowColumnHeaders = true,
                                                ShowGroupFooters = true
                                            };

                    contractsDataGrid.Export(stream, exportOptions);
                    MessageBox.Show(
                        string.Format("Реестр договоров успешно экспортирован в файл {0}", dialog.FileName),
                        "Экспорт реестра договоров", MessageBoxButton.OK, MessageBoxImage.Information);
                }

            }
        }



        private void LoadState()
        {
            _settings = new RadGridViewSettings(contractsDataGrid);
            _settings.LoadState();

        }

        private void SetContextItems()
        {
            var vm = DataContext.CastTo<ContractRepositoryViewBasedViewModel>();
            vm.ContextItems = contractsDataGrid.Items;
        }



        private void SaveState(bool saveFilterDesc, bool saveGroupDesc, bool saveSort)
        {
            if (_settings != null)

                _settings.SaveState(saveFilterDesc, saveGroupDesc, saveSort);
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            SaveState(false, false, false);

        }

        private void contractsDataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var cvm = DataContext.CastTo<ContractRepositoryViewBasedViewModel>(); 
            if (cvm.MainViewModel.OpenContractCommand.CanExecute(sender)) 
                DataContext.CastTo<ContractRepositoryViewBasedViewModel>().MainViewModel.OpenContractCommand.Execute(sender);
        }
        
    }
}
